package com.main.common.base.base;

import io.lettuce.core.dynamic.support.ResolvableType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class BaseAssemblerFactory {

    private final Map<Class<?>, BaseAssembler<?,?>> serviceMap = new ConcurrentHashMap<>();

    /**
     * 初始化时扫描所有 BaseAssembler 实现类，并建立泛型类型与 Bean 的映射
     */
    @Autowired
    public void initServiceMap(List<BaseAssembler<?,?>> services) {
        for (BaseAssembler<?,?> service : services) {
            // 解析实现类的泛型参数类型
            Class<?> genericType = resolveRegisterType(service.getClass());
            serviceMap.put(genericType, service);
        }
        System.out.println("serviceMap");
        System.out.println(serviceMap);
    }

    /**
     * 解析类上的泛型参数
     */
    private Class<?> resolveRegisterType(Class<?> clazz) {
        ResolvableType resolvableType = ResolvableType.forClass(clazz).as(BaseAssembler.class);
        return resolvableType.getGeneric(1).resolve();
    }

    /**
     * 根据传入的泛型类型动态获取实现类，递归检查父类
     */
    @SuppressWarnings("unchecked")
    public <E,D> BaseAssembler<E,D> getService(Class<D> type) {
        // 递归查找父类类型
        Class<?> currentType = type;
        while (currentType != null && currentType != Object.class) {
            BaseAssembler<?,?> service = serviceMap.get(currentType);
            if (service != null) {
                return (BaseAssembler<E,D>) service;
            }
            currentType = currentType.getSuperclass();
        }
        System.out.println("serviceMap");
        System.out.println(serviceMap);
        throw new IllegalArgumentException("未找到类型 " + type + " 或其父类对应的注册服务");
    }
}